import React, {Component} from 'react';

class PureComponent extends Component {
    isPureComponent = true;

    //传入新的属性对象和状态对象，然后返回一个是否需要更新的boolean
    shouldComponentUpdate(nextProps, nextState, nextContext) {
      return !shallowEqual(this.props, nextProps) || !shallowEqual(this.state, nextState);
    }
}

//浅比较 比较obj1和obj2是否相等，如果相等的话则返回true，不相等返回false，只比较第一层
function shallowEqual(obj1, obj2) {
  if (obj1 === obj2) return true;

  if (typeof obj1 != 'object' || obj1 === null || typeof obj2 != 'object' || obj2 === null) {
    return false;
  }

  const keys1 = Object.keys(obj1);
  const keys2 = Object.keys(obj2);
  if (keys1.length !== keys2.length) return false;

  //k of 迭代数组  k in 迭代对象
  for (const k of keys1) {
    if (!obj2.hasOwnProperty(k) || obj1[k] !== obj2[k]) return false;
  }

  return true;
}

//深比较
function shadowEqual(obj1, obj2) {
  if (obj1 === obj2) return true;

  //TODO 判断type是否相同 fn?obj?
  if (typeof obj1 != 'object' || obj1 === null || typeof obj2 != 'object' || obj2 === null) {
    return false;
  }

  const keys1 = Object.keys(obj1);
  const keys2 = Object.keys(obj2);
  if (keys1.length !== keys2.length) return false;

  //k of 迭代数组  k in 迭代对象
  for (const k of keys1) {
    if (obj2.hasOwnProperty(k)) {
      if (obj1[k] !== obj2[k]) {
        //TODO 判断type是否相同 fn?obj?
        if (typeof obj1[k] === 'object' && typeof obj2[k] === 'object') {
          return shadowEqual(obj1[k], obj2[k]);
        }
        return false;
      }
      return false;
    } else {
      return false;
    }
  }

  return true;
}

export default PureComponent;

//TODO
const obj1 = {attr: {name: 'ahhh'}};
const obj2 = {attr: {name: 'ahhh'}};
console.log(shallowEqual(obj1, obj2)); //false
